# 注册 登录
from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordRequestForm

import core.login as cl
import utils.jwt, utils.valid
from core import curd
from core.security import get_password_hash
from models import User, Light
from scheams import UserIn_Pydantic, FailureResponse, BaseResponse, Light_Pydantic
from scheams.login import LoginPydantic, TokenPydantic, LoginByIP
from scheams.user import UserLogin_Pydantic, User_Pydantic

login = APIRouter()


@login.post("/login", summary="登录")
async def user_login(login_form: OAuth2PasswordRequestForm = Depends()):
    return await cl.login(User, UserLogin_Pydantic, login_form)


@login.post("/register", summary="注册", response_model=BaseResponse)
async def user_register(user_form: UserIn_Pydantic):
    user_form.password = get_password_hash(user_form.password)
    return await curd.create(User, user_form)


@login.post("/logout", summary="退出登录", response_model=BaseResponse)
async def user_logout():
    pass


@login.post("/token", summary="token验证", response_model=BaseResponse)
async def check_token(token: TokenPydantic):
    payload, msg = utils.jwt.validate_token(token.token)
    if payload is None:
        return FailureResponse(message=msg, code=400)
    else:
        return await cl.get_user_by_username(User, payload["username"], User_Pydantic)


@login.post("/ip", summary="使用ip登录", response_model=BaseResponse)
async def login_by_ip(login_form: LoginByIP):
    if not utils.valid.is_valid_ip(login_form.ip): return FailureResponse(message="非法的IP地址")
    return await cl.login_by_ip(Light, login_form, Light_Pydantic)
